<template>
  <div>
    <Header :left="true" leftText="返回" title="夜班人员指派" />
    <div>
      <!-- 标签 -->
      <van-row style="margin-top:80px;">
        <van-col><van-image width="40" height="30" style="margin-left:-10px;" src="assets/block.png"/></van-col>
        <van-col class="message">夜班指派</van-col>
      </van-row>
    </div>
    <!-- 分割线 -->
    <div style="background-color: #F5F5F5;height:5px;"><span></span></div>
    <!-- 数据信息 -->
    <div class="divMessage">
      <Field
        v-model="form.siteName"
        :readonly="true"
        size="small"
        style="color:#FF7F50;height:40px;"
        center
        colon
        label="工厂"
      />
      <Field
        v-model="helpUserNameStr"
        :readonly="true"
        size="small"
        class="Field"
        center
        colon
        placeholder="————选择人员————"
        @click="openSelectUser"
        right-icon="assets/right.png"
        label="人员"
      />

      <Field
        v-model="form.startTime"
        readonly
        clickable
        size="large"
        placeholder="请选择开始时间"
        center
        colon
        label="开始时间"
        right-icon="assets/right.png"
        @click="sourceShowPicker = true"
      />
      <van-popup v-model="sourceShowPicker" round position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="datetime"
          title="选择开始时间"
          :columns="columns"
          @confirm="sourceOnConfirm"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
          @cancel="sourceShowPicker = false"
        />
      </van-popup>
      <Field
        v-model="form.endTime"
        readonly
        clickable
        size="large"
        placeholder="请选择结束时间"
        center
        colon
        label="结束时间"
        right-icon="assets/right.png"
        @click="sourceShowPickerEnd = true"
      />
      <van-popup v-model="sourceShowPickerEnd" round position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="datetime"
          title="选择结束时间"
          :columns="columns"
          @confirm="sourceOnConfirmEnd"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
          @cancel="sourceShowPickerEnd = false"
        />
      </van-popup>
      <Field
        v-model="form.status"
        :readonly="true"
        size="small"
        style="color:#FF7F50;height:40px;"
        center
        colon
        right-icon="assets/right.png"
        label="状态"
        @click="statusShow = true"
      />
      <van-popup v-model="statusShow" round position="bottom">
        <van-picker
          showPicker="false"
          title="状态选择"
          value-key="text"
          show-toolbar
          @confirm="statusConfirm"
          :columns="statusList"
          @cancel="statusShow = false"
          default-index="0"
        />
      </van-popup>
    </div>
    <!-- 底部按钮 -->
    <van-button :block="true" @click="close" class="buttonStart" type="primary" text="取消" />
    <van-button :block="true" @click="save" class="buttonEnd" type="primary" text="保存" />
  </div>
</template>
<script>
import {
  Icon,
  Button,
  CellGroup,
  Cell,
  Field,
  Loading,
  tab,
  Uploader,
  tabs,
  Col,
  Row,
  Image as VanImage,
  Divider,
  Checkbox,
  Pagination,
  Panel,
  Toast,
  Dialog,
  popup,
  Popup,
  Picker,
  DatetimePicker,
} from 'vant'
import { _httpClient } from '@/libs/api'
import { storage } from '@/libs/utils'
import { removeToken, getToken, setBaseApiFrefix, getBaseApiFrefix } from '@/libs/auth'
Vue.use(Cell)
Vue.use(CellGroup)
Vue.use(tab)
Vue.use(tabs)
Vue.use(Button)
Vue.use(Col)
Vue.use(Row)
Vue.use(Icon)
Vue.use(VanImage)
Vue.use(Divider)
Vue.use(Checkbox)
Vue.use(Pagination)
Vue.use(Panel)
Vue.use(Dialog)
Vue.use(Picker)
Vue.use(popup)
Vue.use(Uploader)
Vue.use(Loading)
Vue.use(DatetimePicker)
import Header from '@/components/header.vue'
import apicloud from '@/libs/apicloud'
export default {
  components: {
    Button,
    Header,
    Icon,
    CellGroup,
    Cell,
    Field,
    tab,
    tabs,
    Col,
    Row,
    Picker,
    Popup,
    DatetimePicker,
  },

  data() {
    return {
      statusList: [{ text: '停止' }, { text: '启动' }],
      btnLoading: false,
      winName: '', //窗口名
      user: [], //当前登录用户
      //多媒体文件
      photoList: [
        //图片
      ],
      statusShow: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2030, 10, 1),
      currentDate: null,
      helpUser: [], //协助人
      helpUserStr: '', //协助人拼接字符串
      helpUserNameStr: '', //协助人拼接字符串

      sourceShowPicker: false,
      sourceShowPickerEnd: false,
      allSelected: false,
      selectFont: '一键勾选',
      screenWidth: 0,
      checked: true,
      active: 2,
      currentPage: 1,
      fileUrl: '',

      columns: [{ fault_key: '1', fault_value: '机械故障' }],
    }
  },
  created: function() {
    let oldHight = api.winWidth
    this.screenWidth = oldHight
    this.user = JSON.parse(storage.get('user'))
    this.minDate = new Date(new Date().getFullYear() - 1, 0, 1)
    this.maxDate = new Date(new Date().getFullYear() + 3, 0, 1)
    this.form = api.pageParam.equip

    let tkn = getToken()
    if (!tkn) {
      api.openWin({
        name: 'login',
        url: './login-login.html',
        rect: {
          x: 0,
          y: 150,
          w: api.winWidth,
          h: api.winHeight,
        },
      })
    }
    //页面赋值
    this.form = api.pageParam.equip
    if (this.form.status == '0') {
      this.form.status = '停止'
    } else {
      this.form.status = '启动'
    }
    this.helpUserStr = this.form.userName
    this.helpUserNameStr = this.form.userName
    // alert(JSON.stringify(this.form))
  },
  methods: {
    statusConfirm(value) {
      this.statusShow = false
      this.form.status = value.text
    },
    sourceOnConfirmEnd(value) {
      this.sourceShowPickerEnd = false
      if (value === undefined) {
        return
      }
      let year = value.getFullYear() //年
      let month = value.getMonth() + 1 //月
      let day = value.getDate() //日
      let hour = value.getHours() //时
      let minute = value.getMinutes() //分
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      // alert(`${year}-${month}-${day} ${hour}:${minute}:00`)
      this.form.endTime = `${year}-${month}-${day} ${hour}:${minute}:00`
    },
    //下拉框确认确认
    sourceOnConfirm(value) {
      this.sourceShowPicker = false
      if (value === undefined) {
        return
      }
      let year = value.getFullYear() //年
      let month = value.getMonth() + 1 //月
      let day = value.getDate() //日
      let hour = value.getHours() //时
      let minute = value.getMinutes() //分
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      // alert(`${year}-${month}-${day} ${hour}:${minute}:00`)
      this.form.startTime = `${year}-${month}-${day} ${hour}:${minute}:00`
    },
    close() {
      api.closeWin()
    },

    //保存
    async save() {
      let _this = this
      if (_this.helpUserStr == '' || _this.helpUserStr == undefined) {
        Dialog.alert({
          message: '人员不能为空',
            theme: 'round-button',
        }).then(() => {
          // on close
        })
        return
      }
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: '保存中...',
      })
      if (_this.form.status == '停止') {
        _this.form.status = '0'
      } else {
        _this.form.status = '1'
      }
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/equipment/save', {
          body: {
            id: _this.form.id,
            startTime: _this.form.startTime,
            endTime: _this.form.endTime,
            userName: _this.helpUserStr,
            status: _this.form.status,
            siteKey: _this.user.site,
          },
        })
        if (res.code === 200) {
          Toast.clear()
          Dialog.alert({
            message: res.msg,
              theme: 'round-button',
          })
          // .then(() => {})
          // api.sendEvent({
          //   name: 'result',
          //   extra: {
          //     item: _this.form,
          //   },
          // })
          // api.closeWin()
          api.closeToWin({
            name: 'root',
          })
          // _this.reset()
        } else {
          Toast.fail(res.msg)
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e))
      }
    },

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      }
      return value
    },
    //协助人选择
    openSelectUser() {
      let _this = this
      api.openWin({
        name: 'personSelect',
        url: './equipment-personSelect.html',
        type: 'fade',
        pageParam: {
          siteKey: _this.user.site,
        },
      })
      api.addEventListener(
        {
          name: 'resultUser',
        },
        function(ret, err) {
          if (ret.value.selectUser.length != 0) {
            _this.helpUser = ret.value.selectUser
            if (_this.helpUser.length > 0) {
              _this.helpUserStr = ''
              _this.helpUserNameStr = ''
              _this.helpUserStr = _this.helpUser[0].userAccound
              _this.helpUserNameStr = _this.helpUser[0].userName
            }
          }
        }
      )
    },
  },
}
</script>
<style>
body {
  background-color: White;
}

.clickbtn {
  width: 1;
  margin: 5px 10px;
  line-height: 45px;
  border: 1px #ccc dashed;
  text-align: center;
}
.buttonRight {
  position: fixed;
  margin-top: -40px;
  right: 10px;
  width: 85px;
  height: 40px;
  background-color: #1c6c8d;
  border-color: #1c6c8d;
}
.buttonStart {
  position: fixed;
  bottom: 3px;
  left: 5px;
  width: 45%;
  height: 30px;
  background-color: #ff9933;
  border-color: #ff9933;
  font-size: 12px;
}
.buttonEnd {
  position: fixed;
  bottom: 3px;
  right: 5px;
  width: 45%;
  height: 30px;
  background-color: #1c6c8d;
  border-color: #1c6c8d;
  font-size: 12px;
}

.message {
  font-size: 15px;
  margin-top: 5px;
  margin-left: -10px;
  font-weight: bold;
}
.divStyle {
  border: 1px solid #dcdcdc;
  border-top-width: 3px;
  border-left-width: 3px;
  margin-left: 5px;
  margin-right: 4px;
  margin-top: 4px;
}
.pagination {
  position: fixed;
  bottom: 15px;
  width: 300px;
  margin-left: 10%;
  color: rgb(0, 0, 255);
  text-align: center;
}
.divMedia {
  margin-top: 0px;
  height: 230px;
  border: solid #dcdcdc;
  margin-left: 5px;
  margin-right: 15px;
  border-top-width: 4px;
  border-left-width: 4px;
  border-right-width: 1px;
  border-bottom-width: 1px;
}

.divMessage {
  margin-top: 0px;
  border-top-width: 4px;
  border-left-width: 4px;
  border-right-width: 1px;
  border-bottom-width: 1px;
}
</style>
